/**
 * 性能分析脚本
 * 分析构建产物的大小、依赖关系和性能指标
 */

import fs from 'fs'
import path from 'path'
import { execSync } from 'child_process'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

/**
 * 分析构建产物大小
 */
function analyzeBundleSize() {
  console.log('📊 分析构建产物大小...\n')
  
  const distPath = path.join(__dirname, '../dist')
  
  if (!fs.existsSync(distPath)) {
    console.error('❌ dist 目录不存在，请先运行构建命令')
    return
  }
  
  const stats = {
    totalSize: 0,
    files: [],
    categories: {
      js: { size: 0, count: 0 },
      css: { size: 0, count: 0 },
      images: { size: 0, count: 0 },
      fonts: { size: 0, count: 0 },
      audio: { size: 0, count: 0 },
      other: { size: 0, count: 0 }
    }
  }
  
  function analyzeDirectory(dir, relativePath = '') {
    const files = fs.readdirSync(dir)
    
    files.forEach(file => {
      const filePath = path.join(dir, file)
      const relativeFilePath = path.join(relativePath, file)
      const stat = fs.statSync(filePath)
      
      if (stat.isDirectory()) {
        analyzeDirectory(filePath, relativeFilePath)
      } else {
        const size = stat.size
        const ext = path.extname(file).toLowerCase()
        
        stats.totalSize += size
        stats.files.push({
          path: relativeFilePath,
          size: size,
          sizeFormatted: formatBytes(size)
        })
        
        // 分类统计
        if (['.js', '.mjs'].includes(ext)) {
          stats.categories.js.size += size
          stats.categories.js.count++
        } else if (ext === '.css') {
          stats.categories.css.size += size
          stats.categories.css.count++
        } else if (['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp'].includes(ext)) {
          stats.categories.images.size += size
          stats.categories.images.count++
        } else if (['.woff', '.woff2', '.ttf', '.eot', '.otf'].includes(ext)) {
          stats.categories.fonts.size += size
          stats.categories.fonts.count++
        } else if (['.mp3', '.wav', '.ogg', '.m4a'].includes(ext)) {
          stats.categories.audio.size += size
          stats.categories.audio.count++
        } else {
          stats.categories.other.size += size
          stats.categories.other.count++
        }
      }
    })
  }
  
  analyzeDirectory(distPath)
  
  // 排序文件（按大小降序）
  stats.files.sort((a, b) => b.size - a.size)
  
  // 输出统计结果
  console.log(`📦 总大小: ${formatBytes(stats.totalSize)}`)
  console.log(`📄 文件数量: ${stats.files.length}\n`)
  
  console.log('📊 分类统计:')
  Object.entries(stats.categories).forEach(([category, data]) => {
    if (data.count > 0) {
      const percentage = ((data.size / stats.totalSize) * 100).toFixed(1)
      console.log(`  ${getCategoryIcon(category)} ${category.toUpperCase()}: ${formatBytes(data.size)} (${data.count} 文件, ${percentage}%)`)
    }
  })
  
  console.log('\n📋 最大的文件:')
  stats.files.slice(0, 10).forEach((file, index) => {
    const percentage = ((file.size / stats.totalSize) * 100).toFixed(1)
    console.log(`  ${index + 1}. ${file.path} - ${file.sizeFormatted} (${percentage}%)`)
  })
  
  // 性能建议
  console.log('\n💡 性能建议:')
  if (stats.categories.js.size > 500 * 1024) {
    console.log('  ⚠️  JavaScript 文件较大，考虑进一步代码分割')
  }
  if (stats.categories.images.size > 1024 * 1024) {
    console.log('  ⚠️  图片文件较大，考虑压缩或使用 WebP 格式')
  }
  if (stats.categories.css.size > 100 * 1024) {
    console.log('  ⚠️  CSS 文件较大，考虑移除未使用的样式')
  }
  if (stats.totalSize > 2 * 1024 * 1024) {
    console.log('  ⚠️  总体积较大，考虑启用更激进的压缩')
  }
  
  return stats
}

/**
 * 分析依赖关系
 */
function analyzeDependencies() {
  console.log('\n🔍 分析依赖关系...\n')
  
  try {
    const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8'))
    
    const dependencies = packageJson.dependencies || {}
    const devDependencies = packageJson.devDependencies || {}
    
    console.log(`📦 生产依赖: ${Object.keys(dependencies).length}`)
    Object.entries(dependencies).forEach(([name, version]) => {
      console.log(`  • ${name}: ${version}`)
    })
    
    console.log(`\n🛠️  开发依赖: ${Object.keys(devDependencies).length}`)
    Object.entries(devDependencies).forEach(([name, version]) => {
      console.log(`  • ${name}: ${version}`)
    })
    
    // 检查过时的依赖
    console.log('\n🔄 检查过时依赖...')
    try {
      const outdated = execSync('npm outdated --json', { encoding: 'utf8' })
      const outdatedPackages = JSON.parse(outdated)
      
      if (Object.keys(outdatedPackages).length > 0) {
        console.log('⚠️  发现过时依赖:')
        Object.entries(outdatedPackages).forEach(([name, info]) => {
          console.log(`  • ${name}: ${info.current} → ${info.latest}`)
        })
      } else {
        console.log('✅ 所有依赖都是最新的')
      }
    } catch (error) {
      console.log('ℹ️  无过时依赖或检查失败')
    }
    
  } catch (error) {
    console.error('❌ 分析依赖失败:', error.message)
  }
}

/**
 * 运行性能测试
 */
function runPerformanceTests() {
  console.log('\n🚀 运行性能测试...\n')
  
  try {
    // 运行单元测试
    console.log('🧪 运行单元测试...')
    execSync('npm run test', { stdio: 'inherit' })
    
    // 运行类型检查
    console.log('\n🔍 运行类型检查...')
    execSync('npm run type-check', { stdio: 'inherit' })
    
    // 运行代码检查
    console.log('\n🔧 运行代码检查...')
    execSync('npm run lint', { stdio: 'inherit' })
    
    console.log('\n✅ 所有测试通过')
    
  } catch (error) {
    console.error('❌ 测试失败:', error.message)
  }
}

/**
 * 生成性能报告
 */
function generateReport(bundleStats) {
  console.log('\n📄 生成性能报告...\n')
  
  const report = {
    timestamp: new Date().toISOString(),
    bundleSize: {
      total: bundleStats.totalSize,
      totalFormatted: formatBytes(bundleStats.totalSize),
      categories: Object.fromEntries(
        Object.entries(bundleStats.categories).map(([key, value]) => [
          key,
          {
            size: value.size,
            sizeFormatted: formatBytes(value.size),
            count: value.count,
            percentage: ((value.size / bundleStats.totalSize) * 100).toFixed(1)
          }
        ])
      )
    },
    largestFiles: bundleStats.files.slice(0, 10).map(file => ({
      path: file.path,
      size: file.size,
      sizeFormatted: file.sizeFormatted,
      percentage: ((file.size / bundleStats.totalSize) * 100).toFixed(1)
    })),
    recommendations: generateRecommendations(bundleStats)
  }
  
  const reportPath = path.join(__dirname, '../performance-report.json')
  fs.writeFileSync(reportPath, JSON.stringify(report, null, 2))
  
  console.log(`📊 性能报告已保存到: ${reportPath}`)
  
  return report
}

/**
 * 生成性能建议
 */
function generateRecommendations(stats) {
  const recommendations = []
  
  if (stats.categories.js.size > 500 * 1024) {
    recommendations.push({
      type: 'warning',
      category: 'javascript',
      message: 'JavaScript 文件较大，建议进一步代码分割',
      impact: 'high'
    })
  }
  
  if (stats.categories.images.size > 1024 * 1024) {
    recommendations.push({
      type: 'warning',
      category: 'images',
      message: '图片文件较大，建议压缩或使用现代格式（WebP/AVIF）',
      impact: 'medium'
    })
  }
  
  if (stats.categories.css.size > 100 * 1024) {
    recommendations.push({
      type: 'info',
      category: 'css',
      message: 'CSS 文件较大，考虑移除未使用的样式',
      impact: 'low'
    })
  }
  
  if (stats.totalSize > 2 * 1024 * 1024) {
    recommendations.push({
      type: 'warning',
      category: 'overall',
      message: '总体积较大，建议启用更激进的压缩和优化',
      impact: 'high'
    })
  }
  
  if (stats.totalSize < 500 * 1024) {
    recommendations.push({
      type: 'success',
      category: 'overall',
      message: '构建产物大小优秀，保持当前优化策略',
      impact: 'positive'
    })
  }
  
  return recommendations
}

/**
 * 格式化字节大小
 */
function formatBytes(bytes) {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 获取分类图标
 */
function getCategoryIcon(category) {
  const icons = {
    js: '📜',
    css: '🎨',
    images: '🖼️',
    fonts: '🔤',
    audio: '🔊',
    other: '📄'
  }
  return icons[category] || '📄'
}

/**
 * 主函数
 */
async function main() {
  console.log('🔍 Vue 跑酷游戏 - 性能分析工具\n')
  console.log('='.repeat(50))
  
  const bundleStats = analyzeBundleSize()
  if (!bundleStats) {
    return
  }
  
  analyzeDependencies()
  runPerformanceTests()
  const report = generateReport(bundleStats)
  
  console.log('\n' + '='.repeat(50))
  console.log('✅ 性能分析完成！')
  
  // 输出总结
  console.log('\n📋 总结:')
  console.log(`  📦 构建大小: ${formatBytes(bundleStats.totalSize)}`)
  console.log(`  📄 文件数量: ${bundleStats.files.length}`)
  console.log(`  💡 建议数量: ${report.recommendations.length}`)
  
  const highImpactRecommendations = report.recommendations.filter(r => r.impact === 'high')
  if (highImpactRecommendations.length > 0) {
    console.log(`  ⚠️  高优先级建议: ${highImpactRecommendations.length}`)
  }
}

// 运行分析
const isMainModule = process.argv[1] && (
  process.argv[1].endsWith('performance-analysis.js') ||
  import.meta.url === `file://${process.argv[1]}`
)

if (isMainModule) {
  main().catch(console.error)
}

export {
  analyzeBundleSize,
  analyzeDependencies,
  runPerformanceTests,
  generateReport
}